package cn.core.tool.interceptors;

import cn.core.tool.context.CoreContextData;
import cn.core.tool.exception.CoreException;
import cn.core.tool.util.CoreTool;
import cn.core.tool.util.Res;
import com.google.gson.Gson;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.LinkedHashMap;

/**
 * 响应加密
 */
@RestControllerAdvice
@ConditionalOnProperty(prefix = "proconf", name = "http-response-body-encode", havingValue = "true")
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice<Object> {

  @Resource
  private Gson gson;

  @Override
  public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    if (body.getClass().equals(Res.class)) {
      return new Res<>(CoreTool.encodeAES(gson.toJson(body), CoreContextData.getCurrentContextData() != null && CoreContextData.getCurrentContextData().getAesKey() != null ? CoreContextData.getCurrentContextData().getAesKey() : CoreTool.AES_KEY));
    }
    return body;
  }

}
